package ch.hc2.registration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author msyfrig
 */
public class KeySolver {
    private static final byte                      ALPHABET_LENGTH  = 26;
    private static final byte                      ASCII_SMALL_A    = 97;

    // <char to replace, char to replace it with>
    private static final Map<Character, Character> KEYMAP           = new HashMap<>(
                                                                            ALPHABET_LENGTH);
    private static final List<Character>           CYBERSPACE_LIST  = new ArrayList<>(
                                                                            ALPHABET_LENGTH);

    // set this one, can be generated with generateRandomKey
    private static final String                    KEY              = "ysemacknvwlgdburijopqxthzf";
    // set this one,
    private static final String                    START_CYBERSPACE = "lgfizrhncsvqupxyjeodawtkbm";

    static {
        for (int i = 0; i < ALPHABET_LENGTH; i++) {
            // fill the value with the KEY sequence as many times as possible.
            // But normally the key has the same length as the alphabet, so each
            // key maps to another, dunno if this is even allowed. implemented
            // anyways, because fuck it
            KEYMAP.put(Character.valueOf((char) (i + ASCII_SMALL_A)),
                    Character.valueOf(KEY.charAt((i % KEY.length()))));
        }

        for (int j = 0; j < START_CYBERSPACE.length(); j++) {
            CYBERSPACE_LIST.add(Character.valueOf(START_CYBERSPACE.charAt(j)));
        }
    }

    public static String generateRandomKey() {
        List<Character> foo = new ArrayList<>(26);
        for (int i = ASCII_SMALL_A; i < (ASCII_SMALL_A + 26); i++) {
            foo.add(Character.valueOf((char) i));
        }

        Collections.shuffle(foo);
        StringBuilder sb = new StringBuilder(ALPHABET_LENGTH);
        for (Character c : foo) {
            sb.append(c);
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(KEYMAP);

        int counter = 0;

        // copy the original cyberspace list
        List<Character> temp1 = new ArrayList<>(CYBERSPACE_LIST);
        do {
            List<Character> temp2 = new ArrayList<>(ALPHABET_LENGTH);
            for (int i = 0; i < temp1.size(); i++) {
                Character charToReplace = temp1.get(i);
                Character newChar = KEYMAP.get(charToReplace);
                temp2.add(newChar);
            }
            counter++;
            System.out.println(temp2);
            temp1 = temp2;
        }
        while (!temp1.equals(CYBERSPACE_LIST));

        System.out.println(counter);

    }
}
